const Koa = require('koa')
const app = new Koa()
const cors = require('koa2-cors')
const bodyParser = require('koa-bodyparser')
const { connectDb, initSchema } = require('./database/index')

app.use(cors({
  credentials: true,
  origin: 'http://localhost:3000'
}))
app.use(bodyParser())
connectDb()
initSchema()

app.use(async (ctx, next) => {
  const { url } = ctx.request
  const whiteList = ['/user/login', '/user/register']
  console.log(1212, url);
  if (whiteList.includes(url)) {
    await next()
  } else {
    const userId = ctx.cookies.get('userId')
    if (userId) {
      ctx.body = {
        code: 401, // 未登录或者登录过期
        msg: '您还未登录或者登录期已过，请重新登录'
      }
    } else {
      await next()
    }
  }
})
const Router = require('koa-router')
const router = new Router()
const UserRouter = require('./database/api/user')
router.use('/user', UserRouter.routes())
app.use(router.routes()).use(router.allowedMethods())

app.listen(3033, () => {
  console.log('server is running %s', 3033)
})